package com.infinit.easyreader.ui;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.infinit.easyreader.R;
import com.infinit.easyreader.entity.RankContent;
import com.infinit.easyreader.fragment.RankListFragment;

import butterknife.Bind;
import butterknife.ButterKnife;

public class BookContentActivity extends AppCompatActivity {

    @Bind(R.id.ibBookContentBack)
    ImageButton ibBookContentBack;
    @Bind(R.id.tvBookContentTitle)
    TextView tvBookContentTitle;
    @Bind(R.id.wvContent)
    WebView wvContent;
    @Bind(R.id.bookContentLoadingProgress)
    ProgressBar bookContentLoadingProgress;

    /**
     * setWebView
     */


    private void setWvContent()

    {

        wvContent.setWebViewClient(new WebViewClient() {


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });


        wvContent.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress < 100) {
                    bookContentLoadingProgress.setVisibility(View.VISIBLE);
                    bookContentLoadingProgress.setProgress(newProgress);
                } else {
                    bookContentLoadingProgress.setVisibility(View.GONE);
                }

                super.onProgressChanged(view, newProgress);
            }
        });


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_content);
        ButterKnife.bind(this);
        RankContent content = getIntent().getParcelableExtra(RankListFragment.INTENT_CONTENT);
        String url = content.getWapURL();
        String title = content.getContentName();
        setWvContent();
        wvContent.loadUrl(url);
        tvBookContentTitle.setText(title);
        setListeners();

    }

    @Override
    public void onBackPressed() {
        if (wvContent.canGoBack()) {
            wvContent.goBack();
        } else {
            super.onBackPressed();
        }
    }


    private void setListeners() {
        ibBookContentBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

}
